#include "AppDelegate.h"

#include "NetworkManager.h"
#include "MainTestScene.h"

AppDelegate::AppDelegate()
{
}

AppDelegate::~AppDelegate() 
{
}

bool AppDelegate::applicationDidFinishLaunching()
{
    // init singleton
    NetworkManager::getInstance();

    // init network manager
    if (NetworkManager::getInstance()->init() == false) {
        CCLOG("init network manager failed");
        return false;
    }

    auto director = cocos2d::Director::getInstance();
    director->setDisplayStats(true);

    // setup opengl view
    auto glview = director->getOpenGLView();
    glview->setDesignResolutionSize(320, 480,
                                    ResolutionPolicy::FIXED_HEIGHT);

    // setup keypad callback
    auto listener = cocos2d::EventListenerKeyboard::create();
    if (!listener) {
      CCLOG("create EventListenerKeyboard failed");
      return false;
    }
    listener->onKeyReleased = CC_CALLBACK_2(AppDelegate::onKeyReleased, this);

    auto event_dispatcher = director->getEventDispatcher();
    event_dispatcher->addEventListenerWithFixedPriority(listener, 100);

    // run main test scene
    auto main_test_scene = MainTestScene::create();
    if (!main_test_scene) {
        CCLOG("create MainTestScene failed");
        return false;
    }
    director->runWithScene(main_test_scene);

    return true;
}

void AppDelegate::applicationDidEnterBackground()
{
    cocos2d::Director::getInstance()->stopAnimation();
}

void AppDelegate::applicationWillEnterForeground()
{
    cocos2d::Director::getInstance()->startAnimation();
}

void AppDelegate::onKeyReleased(cocos2d::EventKeyboard::KeyCode keycode,
                                cocos2d::Event *event)
{
    if (keycode == cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE) {
        cocos2d::Director::getInstance()->end();
    }
}

void AppDelegate::dumpGLViewInfo()
{
    auto glview = cocos2d::Director::getInstance()->getOpenGLView();

    CCLOG("frame_size(width=%.2f, height=%.2f)",
          glview->getFrameSize().width,
          glview->getFrameSize().height);
    CCLOG("visible_area(width=%.2f, height=%.2f)",
          glview->getVisibleSize().width,
          glview->getVisibleSize().height);
    CCLOG("visible_origin(x=%.2f, y=%.2f)",
          glview->getVisibleOrigin().x,
          glview->getVisibleOrigin().y);
}

